package com.motu.vertx.module.utility.webhandler;

import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.SearchCondition;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
public class CrashlogHandler extends BaseWebHandler{
	private static final Logger logger = LoggerFactory.getLogger(CrashlogHandler.class);
	public static final String tableName = "crashlog";
	private static Pool jdbcClientServer = null;

	public static void init(Pool jdbcServer){
		jdbcClientServer = jdbcServer;
	}
	
	/**
	 * 客户端crashlog查询
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void search(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
	    String table = tableName;
		if (json.containsKey("tname")) {
			table = json.getString("tname");
		}
		if (json.containsKey("stime")) {
			json.put("stime", TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			json.put("etime", TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		scList.add(new SearchCondition("stime", ">=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("etime", "<=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("content", "like", null, null));
		scList.add(new SearchCondition("userid", "=", null, null));
		scList.add(new SearchCondition("ver", "=", null, null));
		
		searchFromTable(routingContext, jdbcClientServer, json, table, scList);

	}
	
	/**
	 * 服务crashlog查询
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void searchServercrashlog(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
		if (json.containsKey("stime")) {
			json.put("stime", TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			json.put("etime", TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		scList.add(new SearchCondition("stime", ">=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("etime", "<=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("content", "like", null, null));
		scList.add(new SearchCondition("userid", "=", null, null));
		
		searchFromTable(routingContext, jdbcClientServer, json, "servercrashlog", scList);

	}
	
	/**
	 * carshlog统计
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void count(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		HttpServerResponse response = routingContext.response();
		List<SearchCondition> scList = new ArrayList<>();
		String table = tableName;
		if (json.containsKey("tname")) {
			table = json.getString("tname");
		}
		if (json.containsKey("stime")) {
			json.put("stime", TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			json.put("etime", TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		scList.add(new SearchCondition("stime", ">=", new String[] {"a.addtime"}, null));
		scList.add(new SearchCondition("etime", "<", new String[] {"a.addtime"}, null));
		scList.add(new SearchCondition("ver", "=", null, null));
		JsonArray params = new JsonArray();
		String str_where = getSearchString(scList, json, params);
		String sql = "select b.content,count(1) as num,c.status from (select a.content from " + table + " a where a.id>0 " + str_where + " group by a.content,a.addtime) b";
		sql += " left join crashlog_status c on b.content=c.content group by b.content order by num desc";
		MysqlTool.queryJsonArrayFromDb(jdbcClientServer, sql, params, handler->{
			if (handler.succeeded()){
				JsonObject result = new JsonObject();
				result.put("rows", handler.result());
				sendHttpResponse(response, result);
			} else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response,  handler.cause().getMessage());
			}
		});
	}

	/**
	 * 修改crashlog的处理状态
	 * @param routingContext
	 * @param json
	 * @param adminName
	 * @param client
	 */
	public static void updateCrashlogStatus(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		HttpServerResponse response = routingContext.response();
		String content = json.getString("content");
		int status = json.getInteger("status");
		String sql = "select * from crashlog_status where content = ? limit 1";
		JsonArray params = new JsonArray().add(content);
		MysqlTool.queryJsonArrayFromDb(jdbcClientServer, sql, params, handler->{
			if (handler.succeeded()){
				String sql2 = "";
				if (handler.result().size() > 0) {// 有则更新.无则插入
					sql2 = "update crashlog_status set status = ? where content = ?;";
				} else {
					sql2 = "insert into crashlog_status (status, content) values (?,?);";
				}
				JsonArray params2 = new JsonArray().add(status).add(content);
				MysqlTool.updateToDb(jdbcClientServer, sql2, params2, handler2->{
					if (handler2.succeeded()) {
						sendHttpResponse(response, new JsonObject());
					} else {
						logger.error(handler2.cause().getMessage());
						sendHttpResponseError(response, handler2.cause().getMessage());
					}
				});
			} else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}


	/**
	 * 服务端crashlog统计
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void servercrashlog_count(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		HttpServerResponse response = routingContext.response();
		List<SearchCondition> scList = new ArrayList<>();
		if (json.containsKey("stime")) {
			json.put("stime", TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			json.put("etime", TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		scList.add(new SearchCondition("stime", ">=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("etime", "<", new String[]{"addtime"}, null));
		JsonArray params = new JsonArray();
		String str_where = getSearchString(scList, json, params);
		String sql = "SELECT content,COUNT(1) as num FROM " + "servercrashlog" + " WHERE 1=1 " + str_where;
		sql += " GROUP BY content ORDER BY num DESC ";
		MysqlTool.queryJsonArrayFromDb(jdbcClientServer, sql, params, handler -> {
			if (handler.succeeded()) {
				JsonObject result = new JsonObject();
				result.put("rows", handler.result());
				sendHttpResponse(response, result);
			} else {
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}
}
